function initPollCreator(poll_type, target_id) {
    // Where the function caller wants the poll creator to be rendered
    const container = $(`#${target_id}`);
    container.attr('data-poll-type', poll_type);
    container.addClass('poll-creator-container');
    // actual poll gui
    const gui = $(`
        <div class="mb-3">
            <label class="form-label">Poll Options (2-10 options)</label>
        </div>`);
    // Add button
    const add = $(`
        <a class="float-end text-gradient" id="addPollOption">
            <i class="bi bi-plus"></i> Add
        </a>`);
    // Options container where users can define poll options.
    const optionsContainer = $(`<div id="pollOptionsContainer"></div>`);
    gui.append(add, optionsContainer);
    // When a user clicks the add button, add a new poll option input field.
    add.on('click', function() {
        const optionCount = $('.poll-input-group').length;
        if (optionCount < 10) {
            const optContainer = $(`<div class="input-group poll-input-group mb-2" style="display:none;"></div>`);
            const textInput = $(`<input type="text" class="form-control poll-option-input" placeholder="Option ${optionCount + 1}" maxlength="200">`);
            const removeBtn = $(`<button class="btn btn-outline-danger remove-poll-option" type="button">
                                    <i class="bi bi-x"></i>
                                </button>`);
            optContainer.append(textInput, removeBtn);
            removeBtn.on('click', function() {
                $(this).closest('.poll-input-group').remove();
                _updatePollOptionPlaceholders();
            });
            $('#pollOptionsContainer').append(optContainer);
            optContainer.slideDown(300);
        } else {
            alert("Maximum 10 poll options allowed.");
        }
        if (typeof render_bsi == 'function') {
            render_bsi();
        }
    });
    // Add three options by default
    setTimeout(() => { add.trigger('click'); }, 300);
    setTimeout(() => { add.trigger('click'); }, 600);
    // render the poll creator
    container.empty().append(`
        <div class="alert alert-info">
            <i class="bi bi-info-circle"></i> <strong>Creator Poll</strong>
            Solfray Premium required.
        </div>`,
        gui, `
        <div class="mb-3">
            <label for="pollEndTime" class="form-label">Poll End Time (optional)</label>
            <input type="datetime-local" class="form-control" id="pollEndTime" name="poll_end_time">
            <div class="form-text">
                Leave empty for a poll that never expires. Must be at least 5 minutes in the future.
            </div>
        </div>`);
    container.slideDown(300);
}

function serializePollCreator(postData) {
    var poll_options = [];
    $('.poll-option-input').each(function() {
        const v = $(this).val().trim();
        if (v && typeof v == 'string' && v.length > 0 && poll_options.indexOf(v) == -1) {
            poll_options.push(v);
        }
    });
    if (poll_options.length < 2 || poll_options.length > 10) {
        throw new Error('Poll must have between 2 and 10 options.');
    }
    postData.poll_options = poll_options;
    postData.poll_end_time = $('#pollEndTime').val() ? toUserOffsetTimestamp($('#pollEndTime').val()) : null;
    return postData;
}

function destroyPollCreator() {
    $('.poll-creator-container').slideUp(300, function() {
        $(this).empty().removeClass('poll-creator-container').removeAttr('data-poll-type');
    });
}

function _updatePollOptionPlaceholders() {
    $('.poll-input-group').each(function(index) {
        $(this).find('.poll-option-input').attr('placeholder', `Option ${index + 1}`);
    });
}

function toUserOffsetTimestamp(dtString) {
    const d = new Date(dtString);

    // Get user's offset in minutes (e.g. -300 for EST)
    const offsetMinutes = d.getTimezoneOffset();
    const abs = Math.abs(offsetMinutes);

    const sign = offsetMinutes > 0 ? "-" : "+";
    const hh = String(Math.floor(abs / 60)).padStart(2, "0");
    const mm = String(abs % 60).padStart(2, "0");

    return dtString + sign + hh + ":" + mm;
}
